<template>
    <el-card style="height: 120px;">
        <el-form :inline="true" class="form">
            <el-form-item label="表名:">
                <el-input placeholder="请输入表名" clearable v-model="tableNameLike"></el-input>
            </el-form-item>
            <el-form-item label="数据库名:">
                <el-input placeholder="请输入数据库名" v-model="databaseNameLike"></el-input>
            </el-form-item>
            <el-form-item label="数据源连接名:">
                <el-input placeholder="请输入数据源连接名" v-model="dataSourceNameLike"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" size="default" @click="search">搜索</el-button>
                <el-button type="primary" size="default" @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <el-card style="margin: 10px 0px;">
        <!-- table展示用户信息 -->
        <el-table @selection-change="selectChange" style="margin: 10px 0px;" border :data="tableConfigArr">
            <el-table-column label="#" align="center" type="index"></el-table-column>
            <el-table-column label="排序" align="center" prop="sort" width="80px"></el-table-column>
            <el-table-column label="表名" align="center" prop="tableName" show-overflow-tooltip
                             width="280px"></el-table-column>
            <el-table-column label="表描述" align="center" prop="tableComment" show-overflow-tooltip
                             width="280px"></el-table-column>
            <el-table-column label="数据源连接名" align="center" prop="dataSourceName"
                             show-overflow-tooltip></el-table-column>
            <el-table-column label="数据库名" align="center" prop="databaseName" show-overflow-tooltip></el-table-column>
            <el-table-column label="同步时间" align="center" prop="updateTime" show-overflow-tooltip>
            </el-table-column>
            <el-table-column label="操作" width="300px" align="center">
                <template #="{ row, $index }">
                    <el-button type="primary" size="small" icon="Setting" @click="configHandle(row)">配置</el-button>
                    <el-popconfirm :title="`你确定要为${row.tableName}表生成代码吗?`" width="260px" @confirm="genCode(row.uuid,row.menuName)">
                        <template #reference>
                            <el-button type="primary" size="small" icon="DocumentAdd">生成代码</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-pagination v-model:current-page="page" v-model:page-size="pageSize" :page-sizes="[5, 7, 9, 11]"
                       :background="true" layout="prev, pager, next, jumper,->,sizes,total" :total="items"
                       @current-change="getHasTableConfig"
                       @size-change="handler"/>
    </el-card>

    <!-- 抽屉组件:展示日志详情 -->
    <el-dialog v-model="dialogVisite" title="配置">
        <el-tabs v-model="activeName" type="border-card" class="demo-tabs">
            <el-tab-pane name="first">
                <template #label>
                         <span class="custom-tabs-label">
                            <span>基础配置</span>
                         </span>
                </template>
                <el-form label-width="120px" :model="tableConfigAddOrUpdateForm" :rules="rules" ref="form">
                    <el-form-item label="作者" prop="author">
                        <el-input placeholder="请你输入作者" v-model="tableConfigAddOrUpdateForm.author"></el-input>
                    </el-form-item>
                    <el-form-item label="后端基础包名" prop="basePack">
                        <el-input placeholder="请你输入职位备注" v-model="tableConfigAddOrUpdateForm.basePack"></el-input>
                    </el-form-item>
                    <el-form-item label="生成本地目录" prop="productLocalPath">
                        <el-input placeholder="请你输入生成本地目录"
                                  v-model="tableConfigAddOrUpdateForm.productLocalPath"></el-input>
                    </el-form-item>
                    <el-form-item label="表名" prop="tableName">
                        <el-input placeholder="请你输入表名" v-model="tableConfigAddOrUpdateForm.tableName"
                                  disabled></el-input>
                    </el-form-item>
                    <el-form-item label="项目名" prop="productName">
                        <el-input placeholder="请你输入项目名" v-model="tableConfigAddOrUpdateForm.productName"></el-input>
                    </el-form-item>
                    <el-form-item label="菜单名称" prop="menuName">
                        <el-input placeholder="请你输入菜单名称" v-model="tableConfigAddOrUpdateForm.menuName"></el-input>
                    </el-form-item>

                    <el-form-item label="上级菜单" prop="parentMenuUuid">
                        <el-select v-model="tableConfigAddOrUpdateForm.parentMenuUuid" placeholder="请选择上级菜单"
                                   @change="handleSelectChange">
                            <el-option
                                    v-for="item in menuOptions.value"
                                    :key="item.uuid"
                                    :label="item.menuName"
                                    :value="item.perms"
                            />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="忽略表前缀" prop="tablePrefixes">
                        <el-input placeholder="请你输入忽略表前缀" v-model="tableConfigAddOrUpdateForm.tablePrefixes"></el-input>
                    </el-form-item>
                    <el-form-item label="编辑继承添加" prop="updateExAdd">
                        <el-select v-model="tableConfigAddOrUpdateForm.updateExAdd" placeholder="请选择是或否">
                            <el-option
                                    v-for="item in TrueOrFalseOptions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="删除类型" prop="delType">
                        <el-select v-model="tableConfigAddOrUpdateForm.delType" placeholder="请选择删除类型类型">
                            <el-option
                                    v-for="item in delTypeOptions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="逻辑删除字段" prop="tablePrefixes" v-if="delColIsShow()">
                        <el-input placeholder="请你输入逻辑删除字段" v-model="tableConfigAddOrUpdateForm.delCol"></el-input>
                    </el-form-item>
                </el-form>
            </el-tab-pane>
            <el-tab-pane label="字段属性配置">
                <el-table :data="colConfigVOList" height="250" style="width: 100%">
                    <el-table-column prop="columnName" label="字段名" width="180"/>
                    <el-table-column prop="columnComment" label="字段描述" width="180"/>
                    <el-table-column prop="addFlag" label="是否添加" width="100">
                        <template #default="{row,$index}">
                            <el-checkbox v-model="row.addFlag"/>
                        </template>
                    </el-table-column>
                    <el-table-column prop="updateFlag" label="是否编辑" width="100">
                        <template #default="{row,$index}">
                            <el-checkbox v-model="row.updateFlag"/>
                        </template>
                    </el-table-column>
                    <el-table-column prop="request" label="是否必传" width="100">
                        <template #default="{row,$index}">
                            <el-checkbox v-model="row.request"/>
                        </template>
                    </el-table-column>
                    <el-table-column prop="voFlag" label="是否显示" width="100">
                        <template #default="{row,$index}">
                            <el-checkbox v-model="row.voFlag"/>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
            <el-tab-pane label="字段查询配置">
                <el-table :data="searchColList" style="width: 100%" max-height="250">
                    <el-table-column prop="colName" label="字段名" width="200">
                        <template #default="scope">
                            <el-select v-model="scope.row.colName" placeholder="请选择查询字段">
                                <el-option
                                        v-for="item in colOptions.value"
                                        :key="item.columnName"
                                        :label="item.columnName"
                                        :value="item.columnName"
                                />
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column prop="searchType" label="查询类型" width="200">
                        <template #default="scope">
                            <el-select v-model="scope.row.searchType" placeholder="请选择字段查询类型">
                                <el-option
                                        v-for="item in colSearchTypeOptions"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                />
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="120">
                        <template #default="scope">
                            <el-button
                                    link
                                    type="primary"
                                    size="small"
                                    @click.prevent="deleteRow(scope.$index)"
                            >
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-button class="mt-4" style="width: 100%" @click="onAddItem">添加查询字段</el-button>
            </el-tab-pane>
        </el-tabs>
        <template #footer>
            <el-button type="primary" size="default" @click="close()">取消</el-button>
            <el-button type="primary" size="default" @click="genCodeConfig">确定</el-button>
        </template>
    </el-dialog>

</template>
<script setup lang="ts">
    import useLayOutSettingStore from '@/store/modules/setting'
    import {onMounted, reactive, ref, getCurrentInstance, ComponentInternalInstance, nextTick} from 'vue';
    import {ElMessage} from 'element-plus';
    import {
      reqAllListCol,
      reqConfigInfo,
      reqTableGenCode,
      reqTableConfigList,
      reqUpdateTableConfig
    } from "@/api/sys/tableConfig";
    import {
        AllColListResponseData,
        ColConfig,
        TableConfigAddOrUpdateForm,
        TableConfigInfo,
        TableConfigListResponseData,
        TableConfigResponseData
    } from "@/api/sys/tableConfig/type";
    import {HandleResponseData, UuidForm} from "../../../api/common/type";
    import {allTopMenu} from "../../../api/business/menu";
    import {MenuAllListResponseData} from "../../../api/business/menu/type";

    let activeName = ref<string>('')
    let searchColList = ref([])
    let colConfigVOList = ref<ColConfig>([])
    let tableConfigVO = ref<TableConfigResponseData>([])
    //默认页码
    let page = ref<number>(0);
    //一页展示几条数据
    let pageSize = ref<number>(5);
    let dataSourceNameLike = ref<string>('');
    let type = ref<number>(1);
    let tableNameLike = ref<string>('');
    let databaseNameLike = ref<string>('');
    //总个数
    let items = ref<number>(0);
    //存储全部用户的数组
    let tableConfigArr = ref<TableConfigResponseData>([]);
    //定义响应式数据控制抽屉的显示与隐藏
    let drawer = ref<boolean>(false);
    let dialogVisite = ref<boolean>(false);

    let tableConfigAddOrUpdateForm = reactive<TableConfigAddOrUpdateForm>({
        author: '',
        basePack: '',
        dataSourceUuid: '',
        fieldPrefixes: '',
        productLocalPath: '',
        productName: '',
        menuName: '',
        parentMenuUuid: '',
        tableName: '',
        tablePrefixes: '',
        colConfigList: [],
        tableSearchAddFormList: [],
        delCol: '',
        delType: '',
        tableUuid: '',
        updateExAdd: ''
    });

    let TableSearchAddFormList = reactive<[]>({
        colName: null,
        searchType: null,
    });

    let batchDelLogForm = reactive<any>({
        ids: []
    });
    const delTypeOptions = [
        {
            value: '1',
            label: '物理删除',
        },
        {
            value: '0',
            label: '逻辑删除',
        }
    ]

    let uuidFrom = reactive<UuidForm>({
      uuid: ''
    });
    let colOptions = reactive<AllColListResponseData>([])
    let menuOptions = reactive<MenuAllListResponseData>([])
    const TrueOrFalseOptions = [
        {
            value: '0',
            label: '否',
        },
        {
            value: '1',
            label: '是',
        }
    ]
    const colSearchTypeOptions = [
        {
            value: 1,
            label: '等值查询',
        },
        {
            value: 2,
            label: '模糊查询',
        },
        {
            value: 3,
            label: '范围查询',
        },
        {
            value: 4,
            label: 'in查询',
        }
    ]
    const value = ref(0)
    //定义响应式数据:收集用户输入进来的关键字
    //获取模板setting仓库
    let settingStore = useLayOutSettingStore();
    //组件挂载完毕
    onMounted(() => {
        getHasTableConfig();
    });

    const deleteRow = (index: number) => {
        searchColList.value.splice(index, 1)
    }

    const close = () => {
        dialogVisite.value = false;
    }
    const genCodeConfig = async () => {
        tableConfigAddOrUpdateForm.tableSearchAddFormList = searchColList.value;
        tableConfigAddOrUpdateForm.colConfigList = colConfigVOList.value
        let result: HandleResponseData = await reqUpdateTableConfig(tableConfigAddOrUpdateForm)
        if (result.code == '200') {
            ElMessage({type: 'success', message: '配置成功'});
        } else {
            ElMessage({type: 'error', message: '配置失败:' + result.msg});
        }
        dialogVisite.value = false;
        await getHasTableConfig(page.value);
    }

    const genCode = async (uuid:string,menuName:string) => {
      uuidFrom.uuid = uuid;
      let result: HandleResponseData = await reqTableGenCode(uuidFrom);
      if (result.code == '200') {
        ElMessage({type: 'success', message: menuName+'代码生成成功'});
      } else {
        ElMessage({type: 'error', message: menuName+'代码生成失败:' + result.msg});
      }
    }


    const onAddItem = () => {
        searchColList.value.push({
            colName: null,
            searchType: null,
        })
    }
    //获取全部已有的用户信息
    const getHasTableConfig = async (pager = 1) => {
        //收集当前页码
        page.value = pager;
        let result: TableConfigListResponseData = await reqTableConfigList(page.value - 1, pageSize.value, tableNameLike.value, databaseNameLike.value,
            dataSourceNameLike.value);
        if (result.code == '200') {
            items.value = result.result.items;
            tableConfigArr.value = result.result.data;
        }
    }
    //分页器下拉菜单的自定义事件的回调
    const handler = () => {
        getHasTableConfig();
    }

    const delColIsShow = () => {
        return tableConfigAddOrUpdateForm.delType == '0';

    }

    //搜索按钮的回调
    const search = () => {
        //根据关键字获取相应的用户数据
        getHasTableConfig();
        //清空关键字
        dataSourceNameLike.value = '';
        databaseNameLike.value = '';
        tableNameLike.value = '';

    }
    //重置按钮
    const reset = () => {
        settingStore.refsh = !settingStore.refsh;
    }

    const configHandle = async (row: TableConfigInfo) => {
        activeName.value = 'first'
        colConfigVOList.value = [];
        colOptions.value = [];
        menuOptions.value = [];
        dialogVisite.value = true;
        let allTopMenuResult: MenuAllListResponseData = await allTopMenu()
        if (allTopMenuResult.code == '200') {
            menuOptions.value = allTopMenuResult.result
        } else {
            ElMessage({type: 'error', message: '获取失败' + allTopMenuResult.msg});
        }
        //全部字段
        let allColListResult: AllColListResponseData = await reqAllListCol(row.tableUuid);
        if (allColListResult.code == '200') {
            colOptions.value = allColListResult.result
        } else {
            ElMessage({type: 'error', message: '获取失败' + allColListResult.msg});
        }
        //表配置
        let tableConfigResult: TableConfigResponseData = await reqConfigInfo(row.tableUuid);
        if (tableConfigResult.code == '200') {
            //字段配置项
            colConfigVOList.value = tableConfigResult.result.colConfigVOList;
            //全部属性
            nextTick(() => {
                tableConfigVO.value = tableConfigResult.result;
            })
        } else {
            ElMessage({type: 'error', message: '获取失败' + tableConfigResult.msg});
        }
        //塞搜索字段
        searchColList.value = tableConfigResult.result.tableSearchVOList;
        //表单赋值
        Object.assign(tableConfigAddOrUpdateForm, row);
        tableConfigAddOrUpdateForm.basePack = 'com.study';
        tableConfigAddOrUpdateForm.author = '董佳明';
        tableConfigAddOrUpdateForm.productLocalPath = 'E:/Program Files/diary_back/';
        tableConfigAddOrUpdateForm.productName = 'study';
        tableConfigAddOrUpdateForm.tablePrefixes = 't_';
    }

    const setStatusButto = (row: any) => {
        if (row.code == '200') {
            return 'success'
        } else {
            return 'danger'
        }
    }
</script>

<style scoped>
    .form {
        justify-content: space-between;
        align-items: center;
    }

    .demo-tabs > .el-tabs__content {
        padding: 32px;
        color: #6b778c;
        font-size: 32px;
        font-weight: 600;
    }

    .demo-tabs .custom-tabs-label .el-icon {
        vertical-align: middle;
    }

    .demo-tabs .custom-tabs-label span {
        vertical-align: middle;
        margin-left: 4px;
    }
</style>
